package com.zhouzhou.fastjava.query.executors;

import com.zhouzhou.fastjava.query.AbstractQueryExecutor;
import com.zhouzhou.fastjava.query.QueryConfiguration;
import com.zhouzhou.fastjava.query.QueryExecutor;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class JdbcTemplateQueryExecutor extends AbstractQueryExecutor implements QueryExecutor {

    private JdbcTemplate jdbcTemplate;

    private boolean showSql;

    public JdbcTemplateQueryExecutor(QueryConfiguration configuration) {
        super(configuration);
        jdbcTemplate = new JdbcTemplate(configuration.getDataSource());
        showSql = configuration.isShowSql();
    }

    @Override
    public <T> T queryForObject(String sql, Class<T> requiredType, Object... args) {
        return jdbcTemplate.queryForObject(sql, requiredType, args);
    }

    @Override
    public List<Map<String, Object>> queryForList(String sql, Object... args) {
        if (showSql) {
            logger.info("SQL: {}", sql.replaceAll("\\s+", " "));
            logger.info("Parameters: {}", Arrays.stream(args).map(r -> r.getClass().getSimpleName() + ":" + r).collect(Collectors.toList()));
        }
        return jdbcTemplate.queryForList(sql, args);
    }

}
